﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace 异步编程基础_04
{
    public class MyTasks
    {
        public void Method1() { Thread.Sleep(100); }
        public string Method1(string s) { Thread.Sleep(100); return s; }
        public int Method2()
        {
            var range = Enumerable.Range(1, 1000);
            var n = range.Sum();
            return n;
        }
        public Tuple<int, int> Method3(int n1, int n2)
        {
            Tuple<int, int> result = Tuple.Create(n1 / n2, n1 % n2);
            Thread.Sleep(100);
            return result;
        }
    }

    class Program
    {

        private static MyTasks t = new MyTasks();
        private static int i;


        static void Main(string[] args)
        {
            var task = DoAsync();
            task.Wait();
        }

        private static async Task DoAsync()
        {
            await Task.Run(() => t.Method1());
            Console.WriteLine("任务1执行完毕");

            var sum = await Task.Run(() => t.Method2());
            Console.WriteLine("任务2计算1-1000的和是{0}：", sum);

            var a = await Task.Run(() => t.Method3(39, 8));
            Console.WriteLine("任务3 (求39除以8的商和余数)结果为: {0}, {1}", a.Item1, a.Item2);
            while (i < 10)
            {
                //Task. run方法返回类型为Task<String>, await关键字等待任务返回String类型
                var s1 = await Task.Run(() => t.Method1("a "));
                //Task. run方法返回类型为Task<String>, await关键字等待任务返回String类型
                var s2 = await Task.Run(() => t.Method1("b "));
                Console.Write(s1);
                Console.Write(s2);
                i++;
            }
            Console.WriteLine(" \n任务4执行完毕");
            Console.ReadKey();
        }
    }
}
